<template>
  <div class="his-refund-verify">
    <!-- 查询条件和刷新按钮区域 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="d-flex justify-content-between align-items-start">
          <div>
            <h5 class="card-title mb-2">HIS退款验证信息</h5>
            <p class="text-muted small mb-0" v-if="lastUpdateTime">
              最后更新时间: {{ formatDate(lastUpdateTime) }}
            </p>
          </div>
          <button 
            class="btn btn-primary" 
            @click="handleRefresh"
            :disabled="loading"
          >
            <i class="bi bi-arrow-clockwise me-1"></i>
            {{ loading ? '加载中...' : '刷新数据' }}
          </button>
        </div>
        
        <!-- 用户ID验证输入框 -->
        <div class="row mt-3">
          <div class="col-md-4">
            <label for="userIdInput" class="form-label">用户ID验证</label>
            <input 
              type="text" 
              class="form-control" 
              id="userIdInput"
              v-model="userIdInput"
              placeholder="请输入用户ID（如：20108）"
              @input="handleUserIdChange"
            >
            <div class="form-text">
              <i class="bi bi-info-circle me-1"></i>
              请输入用户ID进行查询（如：20108、admin等）
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据表格区域 -->
    <div class="card">
      <div class="card-body">
        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2">正在加载数据，请稍候...</p>
        </div>

        <!-- 空状态 -->
        <div v-else-if="verifyList.length === 0" class="text-center py-5">
          <i class="bi bi-inbox fs-1 text-muted"></i>
          <p class="mt-2" v-if="!userIdInput.trim()">请在上方输入用户ID进行查询</p>
          <p class="mt-2" v-else>用户ID "{{ userIdInput }}" 在最近10分钟内没有退款验证记录</p>
          <button class="btn btn-outline-primary" @click="handleRefresh">
            <i class="bi bi-arrow-clockwise me-1"></i> 刷新数据
          </button>
        </div>

        <!-- 数据表格 -->
        <div v-else class="table-responsive-wrapper">
          <div class="table-responsive">
            <table class="table table-hover table-nowrap">
            <thead>
              <tr>
                <th>患者ID</th>
                <th>患者姓名</th>
                <th>身份证号</th>
                <th>退款金额</th>
                <th>审核人</th>
                <th>录入时间</th>
                <th>二维码</th>
                <th>验证码操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in verifyList" :key="item.id">
                <td>{{ item.patientId }}</td>
                <td>{{ item.patName }}</td>
                <td>{{ formatIdNumber(item.idNumber) }}</td>
                <td>{{ formatAmount(item.refundBalance) }}</td>
                <td>{{ item.userName }}</td>
                <td>{{ formatDate(item.inputDate) }}</td>
                <td>
                  <button 
                    class="btn btn-sm btn-outline-primary"
                    @click="() => copyToClipboard(item.qrCode, '患者二维码')"
                    :disabled="!item.qrCode"
                  >
                    <i class="bi bi-clipboard me-1"></i> 复制患者二维码
                  </button>
                </td>
                <td>
                  <button 
                    class="btn btn-sm btn-danger"
                    @click="() => copyVerifyCodeAndCreateTask(item)"
                    :disabled="item.isGenerating || !item.patientId"
                  >
                    <i class="bi bi-clipboard-check me-1"></i> 
                    {{ item.isGenerating ? '生成中...' : '复制验证码' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
          </div>
          <div class="d-flex justify-content-between align-items-center mt-3">
            <p class="text-muted mb-0">共 {{ totalCount }} 条记录</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Toast 提示 -->
    <div class="toast-container position-fixed bottom-0 end-0 p-3" id="verifyToastContainer"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import api from '@/utils/api'
import { Toast } from 'bootstrap'
import CryptoJS from 'crypto-js'

// 响应式数据
const loading = ref(false)
const verifyList = ref([])
const totalCount = ref(0)
const lastUpdateTime = ref(null)
const userIdInput = ref('')

// 初始化 Toast
let toastInstance = null

// 注释：已改为后端定时任务，不再需要前端定时器

// 组件挂载时初始化
onMounted(() => {
  // 初始化 Bootstrap Toast
  const toastContainer = document.getElementById('verifyToastContainer')
  if (toastContainer) {
    // 创建 Toast 元素
    const toastEl = document.createElement('div')
    toastEl.className = 'toast align-items-center text-white bg-success border-0'
    toastEl.setAttribute('role', 'alert')
    toastEl.setAttribute('aria-live', 'assertive')
    toastEl.setAttribute('aria-atomic', 'true')
    toastEl.innerHTML = `
      <div class="d-flex">
        <div class="toast-body">
          <i class="bi bi-check-circle me-2"></i>
          <span id="toast-message">操作成功</span>
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    `
    toastContainer.appendChild(toastEl)
    
    // 初始化 Bootstrap Toast 实例
     toastInstance = new Toast(toastEl, {
       autohide: true,
       delay: 3000
     })
  }
  
  // 初始化时不自动加载数据，等待用户输入用户ID
  // loadVerifyList()
})

// 组件卸载时的清理（已改为后端定时任务，无需清理前端定时器）
onUnmounted(() => {
  console.log('组件卸载')
})

// 加载验证列表数据
const loadVerifyList = async () => {
  // 检查是否输入了用户ID
  if (!userIdInput.value.trim()) {
    verifyList.value = []
    totalCount.value = 0
    return
  }
  
  loading.value = true
  try {
    // 构建查询参数 - 用户ID作为必需的查询条件
    const params = {
      userId: userIdInput.value.trim()
    }
    
    const response = await api.get('/api/VerifyInfo/recent', { params })
    if (response.data.success) {
      verifyList.value = response.data.data || []
      totalCount.value = verifyList.value.length
      lastUpdateTime.value = new Date()
    } else {
      console.error('加载数据失败:', response.data.message)
      showToast('加载数据失败: ' + response.data.message, 'danger')
    }
  } catch (error) {
    console.error('加载数据出错:', error)
    showToast('加载数据出错，请稍后重试', 'danger')
  } finally {
    loading.value = false
  }
}

// 刷新按钮点击事件
const handleRefresh = () => {
  if (!userIdInput.value.trim()) {
    showToast('请先输入用户ID', 'warning')
    return
  }
  loadVerifyList()
}

// 防抖定时器
let debounceTimer = null

// 用户ID输入框变化事件
const handleUserIdChange = () => {
  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  
  // 设置防抖，500ms后执行查询
  debounceTimer = setTimeout(() => {
    loadVerifyList()
  }, 500)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 格式化金额
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return ''
  return `¥${parseFloat(amount).toFixed(2)}`
}

// 格式化身份证号（中间部分用星号替代）
const formatIdNumber = (idNumber) => {
  if (!idNumber) return ''
  if (idNumber.length <= 10) return idNumber
  return `${idNumber.substring(0, 4)}****${idNumber.substring(idNumber.length - 4)}`
}

// 复制到剪贴板
const copyToClipboard = async (text, type) => {
  console.log('复制操作开始:', { text, type })
  
  if (!text) {
    console.warn(`${type}为空，无法复制`)
    showToast(`${type}为空，无法复制`, 'warning')
    return
  }
  
  try {
    // 优先使用现代 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      console.log('使用现代 Clipboard API')
      await navigator.clipboard.writeText(text)
      console.log('复制成功')
      showToast(`${type}已复制到剪贴板`, 'success')
    } else {
      console.log('使用备用复制方法')
      // 备用方法：使用传统的 execCommand
      fallbackCopyToClipboard(text, type)
    }
  } catch (err) {
    console.error('复制失败:', err)
    // 如果现代API失败，尝试备用方法
    fallbackCopyToClipboard(text, type)
  }
}

// 备用复制方法
const fallbackCopyToClipboard = (text, type) => {
  const textarea = document.createElement('textarea')
  textarea.value = text
  textarea.style.position = 'fixed'
  textarea.style.left = '-999999px'
  textarea.style.top = '-999999px'
  document.body.appendChild(textarea)
  
  try {
    textarea.focus()
    textarea.select()
    const successful = document.execCommand('copy')
    if (successful) {
      showToast(`${type}已复制到剪贴板`, 'success')
    } else {
      showToast(`复制${type}失败，请手动复制`, 'danger')
    }
  } catch (err) {
    console.error('备用复制方法失败:', err)
    showToast(`复制${type}失败，请手动复制`, 'danger')
  } finally {
    document.body.removeChild(textarea)
  }
}

// 生成随机六位数
const generateRandomSixDigits = () => {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

// 生成MD5哈希值
const generateMD5 = (text) => {
  try {
    const hash = CryptoJS.MD5(text).toString()
    console.log('前端生成MD5:', { input: text, hash })
    return hash
  } catch (error) {
    console.error('生成MD5失败:', error)
    throw error
  }
}

// 获取当前用户信息
const getCurrentUser = () => {
  try {
    // 首先尝试从localStorage中获取用户信息对象
    // 尝试多个可能的键名
    const possibleKeys = ['userInfo', 'user', 'currentUser', 'loginUser']
    
    for (const key of possibleKeys) {
      const userInfoStr = localStorage.getItem(key)
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          if (userInfo && userInfo.fullName) {
            console.log(`从localStorage的${key}键获取到用户信息:`, userInfo)
            return {
              fullName: userInfo.fullName,
              username: userInfo.username || userInfo.id || 'admin'
            }
          }
        } catch (e) {
          console.warn(`解析localStorage中的${key}失败:`, e)
        }
      }
    }
    
    // 如果都没找到，输出localStorage中所有的键用于调试
    console.log('localStorage中的所有键:', Object.keys(localStorage))
    console.log('localStorage内容调试:', {
      userInfo: localStorage.getItem('userInfo'),
      user: localStorage.getItem('user'),
      currentUser: localStorage.getItem('currentUser'),
      loginUser: localStorage.getItem('loginUser')
    })
    
    // 如果没有找到userInfo或解析失败，尝试从token中获取
    const token = localStorage.getItem('token')
    if (!token) {
      console.warn('未找到token，使用默认用户信息')
      return {
        fullName: '系统用户',
        username: 'system'
      }
    }
    
    const tokenParts = token.split('.')
    if (tokenParts.length !== 3) {
      console.warn('token格式不正确，使用默认用户信息')
      return {
        fullName: '系统用户',
        username: 'system'
      }
    }
    
    const base64Payload = tokenParts[1]
    // 处理base64编码中的填充问题
    let paddedPayload = base64Payload
    while (paddedPayload.length % 4) {
      paddedPayload += '='
    }
    
    // 替换URL安全的base64字符
    paddedPayload = paddedPayload.replace(/-/g, '+').replace(/_/g, '/')
    
    const payload = JSON.parse(atob(paddedPayload))
    
    return {
      fullName: payload.full_name || payload.name || payload.unique_name || '系统用户',
      username: payload.name || payload.sub || payload.unique_name || 'system'
    }
  } catch (error) {
    console.error('解析用户信息失败:', error)
    // 如果token解析失败，返回默认用户信息而不是抛出错误
    console.warn('使用默认用户信息')
    return {
      fullName: '系统用户',
      username: 'system'
    }
  }
}

// 复制验证码并创建后端定时任务
const copyVerifyCodeAndCreateTask = async (item) => {
  try {
    // 设置生成状态
    item.isGenerating = true
    
    // 使用接口返回的验证码，而不是生成新的
    const verifyCode = item.verifyCode
    if (!verifyCode) {
      showToast('该记录没有验证码信息', 'danger')
      item.isGenerating = false
      return
    }
    
    console.log('使用接口返回的验证码:', verifyCode)
    
    // 复制验证码到剪贴板
    await copyToClipboard(verifyCode, '患者验证码')
    
    // 为定时任务生成随机六位数字（用于加密）
    const randomCode = Math.floor(100000 + Math.random() * 900000).toString()
    console.log('为定时任务生成的随机验证码:', randomCode)
    
    // 生成MD5哈希值
    const md5Hash = generateMD5(randomCode)
    console.log('生成的MD5哈希值:', md5Hash)
    
    // 获取当前用户信息
    const currentUser = getCurrentUser()
    console.log('当前用户信息:', currentUser)
    
    // 创建后端定时任务（延迟时间由服务端配置控制）
    const taskRequest = {
      patientId: item.patientId,
      verifyCode: randomCode,
      refundPassword: md5Hash,
      modifier: currentUser.fullName,
      modifierCardType: '08',
      modifierCardCode: item.idNumber,
      verifyInfoId: item.id  // 添加验证码信息ID，用于精确软删除
    }
    
    console.log('创建定时任务请求参数:', taskRequest)
    
    // 调用后端API创建定时任务
    const response = await api.post('/api/PasswordUpdateTask/create', taskRequest)
    
    if (response.data.success) {
      console.log('定时任务创建成功:', response.data)
      showToast('验证码已复制到剪贴板', 'success')
      
      // 更新UI状态
      item.taskId = response.data.taskId
      item.taskStatus = 'pending'
      // 注意：不要覆盖item.verifyCode，保持原有的真实验证码
    } else {
      console.error('定时任务创建失败:', response.data.message)
      showToast(`定时任务创建失败: ${response.data.message}`, 'danger')
    }
    
  } catch (error) {
    console.error('复制验证码并创建任务失败:', error)
    showToast(`操作失败: ${error.message}`, 'danger')
  } finally {
    // 重置生成状态
    item.isGenerating = false
  }
}

// 查询任务状态
const queryTaskStatus = async (item) => {
  if (!item.taskId) {
    showToast('任务ID不存在', 'warning')
    return
  }
  
  try {
    const response = await api.get(`/api/PasswordUpdateTask/status/${item.taskId}`)
    
    if (response.data.success) {
      const taskData = response.data.task
      item.taskStatus = taskData.status
      
      let statusText = ''
      switch (taskData.status) {
        case 'pending':
          statusText = '等待执行'
          break
        case 'completed':
          statusText = '已完成'
          break
        case 'failed':
          statusText = `执行失败: ${taskData.errorMessage || '未知错误'}`
          break
        case 'cancelled':
          statusText = '已取消'
          break
        default:
          statusText = '未知状态'
      }
      
      showToast(`任务状态: ${statusText}`, taskData.status === 'failed' ? 'danger' : 'info')
    } else {
      showToast(`查询任务状态失败: ${response.data.message}`, 'danger')
    }
  } catch (error) {
    console.error('查询任务状态时发生错误:', error)
    showToast('查询任务状态失败，请稍后重试', 'danger')
  }
}

// 显示 Toast 提示
const showToast = (message, type = 'success') => {
  // 如果没有Toast实例，创建一个简单的alert作为备用
  if (!toastInstance) {
    alert(message)
    return
  }
  
  // 获取 Toast 元素
  const toastEl = document.querySelector('.toast')
  if (!toastEl) {
    alert(message)
    return
  }
  
  // 设置消息内容
  const messageEl = document.getElementById('toast-message')
  if (messageEl) {
    messageEl.textContent = message
  }
  
  // 设置 Toast 类型（颜色）
  const bgClasses = ['bg-success', 'bg-danger', 'bg-warning', 'bg-info']
  bgClasses.forEach(cls => toastEl.classList.remove(cls))
  toastEl.classList.add(`bg-${type}`)
  
  // 显示 Toast
  try {
    toastInstance.show()
  } catch (err) {
    console.error('Toast显示失败:', err)
    alert(message)
  }
}
</script>

<style scoped>
.his-refund-verify {
  padding: 15px;
}

.card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: none;
}

.card-title {
  font-weight: 600;
  color: #333;
}

.table th {
  font-weight: 600;
  background-color: #f8f9fa;
}

.btn-group-sm > .btn, .btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
}

/* Toast 样式 */
.toast {
  min-width: 250px;
}

.toast-body {
  display: flex;
  align-items: center;
}

/* 响应式优化 */
@media (max-width: 1200px) {
  .his-refund-verify {
    padding: 0.75rem;
  }
}

@media (max-width: 768px) {
  .his-refund-verify {
    padding: 0.5rem;
  }
  
  .card-body {
    padding: 0.75rem;
  }
  
  .table th,
  .table td {
    padding: 0.5rem 0.25rem;
    font-size: 0.8rem;
  }
  
  .btn-sm {
    padding: 0.2rem 0.4rem;
    font-size: 0.75rem;
  }
  
  .d-flex.justify-content-between {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 1rem;
  }
}

@media (max-width: 576px) {
  .his-refund-verify {
    padding: 0.25rem;
  }
  
  .card-body {
    padding: 0.5rem;
  }
  
  .table th,
  .table td {
    padding: 0.375rem 0.2rem;
    font-size: 0.75rem;
  }
  
  .btn-sm {
    padding: 0.15rem 0.3rem;
    font-size: 0.7rem;
  }
  
  .card-title {
    font-size: 1rem;
  }
}

/* 表格水平滚动优化 */
.table-responsive-wrapper {
  position: relative;
}

.table-responsive {
  border-radius: 0.375rem;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05);
}

.table-nowrap {
  min-width: 800px;
}

.table-nowrap th,
.table-nowrap td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table-nowrap th:first-child,
.table-nowrap td:first-child {
  position: sticky;
  left: 0;
  background: white;
  z-index: 10;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.table-nowrap th:last-child,
.table-nowrap td:last-child {
  position: sticky;
  right: 0;
  background: white;
  z-index: 10;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
}
</style>